<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="type === '编辑' ? $t('编辑') : $t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="1200px" @close='close' top="5vh">
    <div class="dialogContentBoxMaxHeight90">
      <el-form ref="form" :model="record" :label-width="lang === 'zh'?'140px':'190px'" label-position="left" :rules="rules" style="margin:0 20px;">
        <el-form-item :label="$t('OSPFv3协议状态')" prop="status">
          <el-radio-group v-model="record.status" size='small'>
            <el-radio label="on" class="ospfv3StatusOn">{{$t('开启')}}</el-radio>
            <el-radio label="off" class="ospfv3StatusOff">{{$t('关闭')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('VRF名称')" prop="vrf">
          <el-input v-emoji v-model="record.vrf" ref="ospfVrf" :disabled="type === '编辑' ? true : false" style="width:280px" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('路由器ID')" prop="router_id">
          <template slot="label">{{$t('路由器ID')}}
            <el-tooltip class="item" effect="light" :content="$t('提示信息：路由器ID，默认值0.0.0.0，需设置为接口上的ipv4地址')" placement="top">
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model="record.router_id" ref="ospfRouterId" style="width:280px" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('SPF启动时间')" prop="spf_start">
          <template slot="label">{{$t('SPF启动时间')}}
            <el-tooltip class="item" effect="light" :content="$t('提示信息：SPF启动时间，默认值0毫秒，范围 [0-600000]')" placement="top">
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model="record.spf_start" ref="ospfSpfStart" style="width:280px" size='small'>
            <template slot="append">{{$t('毫秒')}}</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('SPF保持时间')" prop="spf_hold">
          <template slot="label">{{$t('SPF保持时间')}}
            <el-tooltip class="item" effect="light" :content="$t('提示信息：SPF保持时间，默认值50毫秒，范围 [0-600000]')" placement="top">
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model="record.spf_hold" ref="ospfSpfHold" style="width:280px" size='small'>
            <template slot="append">{{$t('毫秒')}}</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('SPF最大等待时间')" prop="spf_max_wait">
          <template slot="label">{{$t('SPF最大等待时间')}}
            <el-tooltip class="item" effect="light" :content="$t('提示信息：SPF最大等待时间，默认值5000毫秒，范围 [0-600000]')" placement="top">
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model="record.spf_max_wait" ref="ospfSpfMaxWait" style="width:280px" size='small'>
            <template slot="append">{{$t('毫秒')}}</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('参考带宽')" prop="reference_bandwidth">
          <template slot="label">{{$t('参考带宽')}}
            <el-tooltip class="item" effect="light" :content="$t('提示信息：参考带宽，默认值1000Mbps，范围 [1-4294967]')" placement="top">
              <i class="el-icon-warning-outline" style="color:#666;font-size:14px;"></i>
            </el-tooltip>
          </template>
          <el-input v-emoji v-model="record.reference_bandwidth" ref="ospfReferenceBandwidth" style="width:280px" size='small'>
            <template slot="append">Mbps</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('区域配置')" prop="regional">
          <div style="border: 1px solid #e6ebf5;padding: 0px 10px 10px;">
            <el-button type="success" size='mini' @click="regionalDialogVisible()" class="regionalAddClick">{{$t('添加')}}</el-button>
            <el-table size='mini' ref="regionalTable" :data="record.regional" tooltip-effect="dark" style="width: 1000px;">
              <el-table-column prop="area" :label="$t('区域')" align='center' min-width="100"></el-table-column>
              <el-table-column prop="type" :label="$t('类型')" align='center' min-width="100"></el-table-column>
              <el-table-column prop="no_summary" label="Totally nssa/stub" align='center' min-width="100">
                <template slot-scope="scope">
                  {{ statusList[scope.row.no_summary] }}
                </template>
              </el-table-column>
              <el-table-column prop="default_originate" :label="$t('是否发布默认路由')" align='center' min-width="100">
                <template slot-scope="scope">
                  {{ statusList[scope.row.default_originate] }}
                </template>
              </el-table-column>
              <el-table-column prop="right" align='center' fixed="right" :label="$t('操作')" width="100">
                <template slot-scope="scope">
                  <el-button type="danger" plain size="mini" @click="regionalDeleteData(scope.row, scope.$index)" :class="'regionalDel' +(scope.$index+1)">{{$t('删除')}}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item :label="$t('接口配置')" prop="interface">
          <div style="border: 1px solid #e6ebf5;padding: 0px 10px 10px;">
            <el-button type="success" size='mini' @click="interfaceDialogVisible()" class="interfaceAddClick">{{$t('添加')}}</el-button>
            <el-table size='mini' ref="interfaceTable" :data="record.interface" tooltip-effect="dark" style="width: 1000px;">
              <el-table-column prop="interface" :label="$t('接口')" align='center' min-width="100"></el-table-column>
              <el-table-column prop="area" :label="$t('区域')" align='center' min-width="100"></el-table-column>
              <el-table-column prop="cost" :label="$t('成本')" align='center' min-width="100"></el-table-column>
              <el-table-column prop="hello_interval" :label="$t('hello定时器')" align='center' min-width="100"></el-table-column>
              <el-table-column prop="dead_interval" :label="$t('dead定时器')" align='center' min-width="100"></el-table-column>
              <el-table-column prop="retransmit_interval" :label="$t('retransmit定时器')" align='center' min-width="100"></el-table-column>
              <el-table-column prop="priority" :label="$t('优先级')" align='center' min-width="100"></el-table-column>
              <el-table-column prop="right" align='center' fixed="right" :label="$t('操作')" width="100">
                <template slot-scope="scope">
                  <el-button type="danger" plain size="mini" @click="interfaceDeleteData(scope.row, scope.$index, '编辑')" :class="'interfaceDel' +(scope.$index+1)">{{$t('删除')}}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
      <regional-dialog v-if="regionalVisible" @addRegional='addRegional' ref="refRegionalVisible"></regional-dialog>
      <interface-dialog v-if="interfaceVisible" @addInterface='addInterface' ref="refInterfaceVisible"></interface-dialog>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="ospfv3AddSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="ospfv3AddClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import {
  getOspfv3Info, // OSPFv3获取协议信息
  addOspfv3, // OSPFv3添加路由
  editOspfv3Info, // OSPFv3编辑信息
  delOspfv3Regional, // OSPFv3删除区域配置
  delOspfv3Interface // OSPFv3删除接口配置
} from '@/api/network/route/dynamicRoute/OSPFv3'
import RegionalDialog from './ospfv3Components/RegionalDialog'
import InterfaceDialog from './ospfv3Components/InterfaceDialog'
import { inputClass } from '@/utils/input-class.js'
export default {
  name: 'Ospfv3Dialog',
  components: {
    RegionalDialog,
    InterfaceDialog
  },
  data () {
    var validateVrf = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (String(value).length > 15) {
        callback(new Error(this.$t('长度不能超过15个字符')))
      } else {
        callback()
      }
    }
    var validateIp = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback()
      } else if (this.isValidIP(value)) {
        callback()
      } else {
        callback(new Error(this.$t('请输入正确的IPv4地址')))
      }
    }
    var validateSpf = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback()
      } else if (isNaN(Number(value))) {
        callback(new Error(this.$t('请输入数字')))
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) > 600000 || Number(value) < 0) {
        callback(new Error(this.$t('请输入0-600000之间的数字')))
      } else {
        callback()
      }
    }
    var validateReferenceBandwidth = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback()
      } else if (isNaN(Number(value))) {
        callback(new Error(this.$t('请输入数字')))
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) > 4294967 || Number(value) < 1) {
        callback(new Error(this.$t('请输入1-4294967之间的数字')))
      } else {
        callback()
      }
    }

    return {
      dialogVisible: false,
      regionalVisible: false, // 路由聚合
      interfaceVisible: false, // 路由聚合
      record: {
        id: '',
        vrf: 'default',
        router_id: '0.0.0.0',
        status: 'off',
        spf_start: '0',
        spf_hold: '50',
        spf_max_wait: '5000',
        reference_bandwidth: '1000',
        regional: [], // 区域配置
        interface: [] // 接口配置
      },
      recordCopy: {
        id: '',
        vrf: 'default',
        router_id: '0.0.0.0',
        status: 'off',
        spf_start: '0',
        spf_hold: '50',
        spf_max_wait: '5000',
        reference_bandwidth: '1000',
        regional: [], // 区域配置
        interface: [] // 接口配置
      },
      lang: this.$i18n.locale,
      type: '',
      statusList: {
        'off': this.$t('关闭'),
        'on': this.$t('开启')
      },
      rules: {
        vrf: [{ required: false, validator: validateVrf, trigger: 'blur' }],
        router_id: [{ required: false, validator: validateIp, trigger: 'blur' }],
        spf_start: [{ required: false, validator: validateSpf, trigger: 'blur' }],
        spf_hold: [{ required: false, validator: validateSpf, trigger: 'blur' }],
        spf_max_wait: [{ required: false, validator: validateSpf, trigger: 'blur' }],
        reference_bandwidth: [{ required: false, validator: validateReferenceBandwidth, trigger: 'blur' }]
      }
    }
  },
  methods: {
    init (data, type) {
      this.dialogVisible = true
      this.type = type
      if (data) {
        this.record.id = data.id
        this.record.vrf = data.vrf
        this.record.router_id = data.router_id
        this.record.status = data.status
        this.record.spf_start = data.spf_start
        this.record.spf_hold = data.spf_hold
        this.record.spf_max_wait = data.spf_max_wait
        this.record.reference_bandwidth = data.reference_bandwidth
        this.record.regional = data.area[0]
        this.record.interface = data.interface[0]
      }
      this.$nextTick(() => {
        const data = ['ospfVrf', 'ospfRouterId', 'ospfSpfStart', 'ospfSpfHold', 'ospfSpfMaxWait', 'ospfReferenceBandwidth']
        inputClass(this.$refs, data)
      })
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.type === '编辑') {
            let formData = JSON.parse(JSON.stringify(this.record))
            formData.regional = JSON.stringify(formData.regional)
            formData.interface = JSON.stringify(formData.interface)
            editOspfv3Info(formData).then(res => {
              if (res.status === 0) {
                this.$messages.success(this.$t('执行成功'))
                this.close()
                this.$parent.listData()
              }
            })
          } else {
            let formData = JSON.parse(JSON.stringify(this.record))
            formData.regional = JSON.stringify(formData.regional)
            formData.interface = JSON.stringify(formData.interface)
            addOspfv3(formData).then(res => {
              if (res.status === 0) {
                this.$messages.success(this.$t('执行成功'))
                this.close()
                this.$parent.listData()
              }
            })
          }
        }
      })
    },
    close () {
      this.type = ''
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.resetFields()
      this.ifnameList = []
      this.isisList = []
    },
    listData () {
      getOspfv3Info({ id: this.record.id }).then(res => {
        if (res.status === 0) {
          this.record.interface = res.info[0].interface[0]
          this.record.regional = res.info[0].area[0]
        }
      })
      this.$emit('listData')
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    },
    regionalDialogVisible () {
      this.regionalVisible = true
      this.$nextTick(() => {
        this.$refs.refRegionalVisible.init(this.type, this.record.id)
      })
    },
    regionalDeleteData (row, index) {
      if (this.type === '编辑') {
        let formData = JSON.parse(JSON.stringify(row))
        formData.id = this.record.id
        delOspfv3Regional(formData).then(res => {
          if (res.status === 0) {
            this.$messages.success(this.$t('删除成功'))
            this.listData()
          }
        })
      } else {
        this.record.regional.splice(index, 1)
      }
    },
    addRegional (data) {
      if (this.type === '编辑') {
        this.listData()
      } else {
        this.record.regional.push(data)
      }
    },
    interfaceDialogVisible () {
      this.interfaceVisible = true
      this.$nextTick(() => {
        this.$refs.refInterfaceVisible.init(this.type, this.record.id, this.record.interface)
      })
    },
    interfaceDeleteData (row, index) {
      if (this.type === '编辑') {
        let formData = JSON.parse(JSON.stringify(row))
        formData.id = this.record.id
        delOspfv3Interface(formData).then(res => {
          if (res.status === 0) {
            this.$messages.success(this.$t('删除成功'))
            this.listData()
          }
        })
      } else {
        this.record.interface.splice(index, 1)
      }
    },
    addInterface (data) {
      if (this.type === '编辑') {
        this.listData()
      } else {
        this.record.interface.push(data)
      }
    },
    isValidIP (ip) {
      let reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
      return reg.test(ip)
    }
  }
}
</script>
